package wty;
// TokenFilter.java
import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class TokenFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        System.out.println("我进入过滤器判断了");

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 设置响应头允许跨域
        httpResponse.setHeader("Access-Control-Allow-Origin", "http://localhost:8081");
        httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
        httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, token");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");

        // 跳过预检请求
        if ("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) {
            httpResponse.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        // 从请求中获取Token
        String token = null;

        // 1. 尝试从cookie中获取Token
        Cookie[] cookies = httpRequest.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    token = cookie.getValue();
                    break;
                }
            }
        }

        // 验证Token
        if (validateToken(token,httpRequest)) {
            // Token有效，继续请求处理
            chain.doFilter(request, response);
        } else {
            // Token无效，拒绝访问
            httpResponse.sendRedirect("http://localhost:8081/main?error=invalid_token");
        }
    }

    @Override
    public void destroy() {
        // 销毁过滤器
    }

    // 验证Token的方法
    private boolean validateToken(String token,HttpServletRequest request) {
        if (token == null || token.trim().isEmpty()) {
            return false;
        }

        try {
            String userId = (String) request.getSession().getAttribute("userId");
            return userId.equals(token);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}